<template>
  <div class="listWapper">
    <customDetailsTopbar title="数智北戴河" flag @back="back" />
    <ul ref="scrollContainer" class="px-1 py-1 ulBox">
      <li
        v-for="(item, index) in verificationDataList"
        :key="item.value"
        @click="setActiveFeature(item, index)"
      >
        <span
          class="feature"
          :class="{ 'active': activeIndex === index }"
        >{{ item.label }}</span>
      </li>
      <div class="iconBox" @click="openPopup">
        <van-icon name="bars" />
      </div>
    </ul>
    <div id="customScroolBox" class="listInner px-1">
      <div class="title_warp">
        <el-form ref="form" :model="form" :label-width="pcdx === 'rhpwk' ? '26vw' : '22vw'">
          <el-form-item :label="pcdx === 'rhpwk' ? '排污口名称：' : pcdx === 'rivers' ? '河流名称：' : '企业名称：'">
            <el-input v-if="pcdx === 'rivers'" v-model="form.hlmc" placeholder="请输入河流名称" size="small" clearable />
            <el-input v-else-if="pcdx === 'rhpwk'" v-model="form.pwkmc" placeholder="请输入排污口名称" size="small" clearable />
            <el-input v-else v-model="form.pcQiyeName" placeholder="请输入企业名称" size="small" clearable />
          </el-form-item>
        </el-form>
        <van-icon name="descending" @click="openSuperSearch" />
      </div>
      <div class="px-1 py-1 d-flex justify-content-center align-items-center">
        <van-button class="customButton" size="small" icon="search" type="primary" @click="handleSuperSearch">查询</van-button>
        <van-button class="customButton" size="small" icon="replay" type="warning" @click="resetSuperSearch">重置</van-button>
        <!-- <van-button v-if="pcdx === 'rhpwk' || pcdx === 'rivers' || pcdx === 'G'" class="customButton" size="small" icon="plus" type="info">增加污染源</van-button>-->
      </div>
      <custom-total-num :title="total" />
      <div class="common_list table-list">
        <el-table :data="listData" style="width: 100%" stripe>
          <el-table-column :label="pcdx === 'rhpwk' ? '排污口名称' : pcdx === 'rivers' ? '河流名称' : '单位名称'" align="center">
            <template v-slot:default="scope">
              <el-link v-if="pcdx === 'rhpwk' || pcdx === 'rivers'" :underline="false" type="primary" @click="openCheckSituationDrawer(scope.row)">{{ scope.row['danweiName'] || scope.row['pwkmc'] || scope.row['hlmc'] }}</el-link>
              <el-link v-else :underline="false" type="primary" @click="openCompanyInformationDrawer(scope.row)">{{ scope.row['danweiName'] || scope.row['pwkmc'] || scope.row['hlmc'] }}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="所在地区" align="center">
            <template v-slot:default="scope">
              <span>{{ scope.row['districtName'] || scope.row['szdq'] }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="pcdx === 'rhpwk' || pcdx === 'rivers' || pcdx === 'G'" label="导航" width="65" align="center">
            <template v-slot:default>
              <span class="navigation" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <customLoadmore ref="customLoadmore" :page-num="form.pageNum" :pages="pages" @load="handlePages" />
    </div>
    <!-- 类型筛选 -->
    <van-popup
      v-model="popupShow"
      position="right"
      :style="{ height: '100%', width: '100%' }"
      @close="onCancel"
    >
      <customDetailsTopbar title="专题-类型筛选" flag @back="onCancel" />
      <van-radio-group v-model="activeIndex">
        <van-cell-group>
          <van-cell
            v-for="(active, index) in verificationDataList"
            :key="active.value"
            clickable
            :title="active.label"
            @click="radioChangeHandler(active, index)"
          >
            <template #right-icon>
              <van-radio :name="index" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>
    </van-popup>
    <!-- 河流和工业企业排查情况 -->
    <van-popup
      v-model="situationParams.checkSituationShow"
      position="right"
      :style="{ height: '100%', width: '100%' }"
      @close="checkSituationCancel"
    >
      <div class="common-details">
        <customDetailsTopbar :title="situationParams.title" flag @back="checkSituationCancel" />
        <checkSituation ref="checkSituationRef" :data-item="situationParams.dataItem" :type="situationParams.type" />
      </div>
    </van-popup>
    <!-- 企业详情信息展示 -->
    <van-popup
      v-model="companyInformationParams.isShow"
      position="right"
      :style="{ height: '100%', width: '100%' }"
      @close="companyInformationParams.isShow = false"
    >
      <div class="common-details">
        <customDetailsTopbar :title="companyInformationParams.title" flag @back="companyInformationParams.isShow = false" />
        <companyInformation ref="companyInformationRef" :data-item="companyInformationParams.dataItem" :type="companyInformationParams.type" />
      </div>
    </van-popup>
    <!-- 高级查询  -->
    <van-popup v-model="superSearch" position="right" :style="{ width: '90%', height: '100%' }" lock-scroll close-on-popstate closeable class="custom-van-pop">
      <div class="pop-vertical-flex">
        <div class="pop-content">
          <div class="customPopCheckbox">
            <div class="checkbox-title">{{ pcdx === 'rhpwk' ? '排污口名称' : pcdx === 'rivers' ? '河流名称' : '企业名称' }}</div>
            <el-input v-if="pcdx === 'rivers'" v-model="form.hlmc" placeholder="请输入河流名称" size="small" clearable />
            <el-input v-else-if="pcdx === 'rhpwk'" v-model="form.pwkmc" placeholder="请输入排污口名称" size="small" clearable />
            <el-input v-else v-model="form.pcQiyeName" placeholder="请输入企业名称" size="small" clearable />
          </div>
          <template v-if="pcdx !== 'rhpwk' && pcdx !== 'rivers'">
            <custom-timer type="year" title="所属年份" :is-interval="false" placeholder="请选择所属年份" :date-value="form.tbnf" @update:dateValue="getTime" />
            <div v-if="pcdx !== 'J' && pcdx !== 'N'" class="customPopCheckbox">
              <div class="checkbox-title">重点行业</div>
              <el-input v-model="keyIndustries" placeholder="请选择重点行业" size="small" clearable @focus="companySelectShow = true" />
            </div>
            <customPopCascade v-if="pcdx !== 'J' && pcdx !== 'N'" ref="customPopCascade" title="行业名称" cascader-title="行业名称" :list="industryListData" @change="cascadeChange" @clearData="form.industry = '';getIndustryByCodeSHandler()" />
            <customPopCheckbox v-if="pcdx !== 'J' && pcdx !== 'N'" title="企业基本信息类型" :list="enterpriseBaseInfoType" :check-value.sync="form.g101_1" />
            <customPopCheckbox v-if="pcdx !== 'J' && pcdx !== 'N'" title="涉水类型" :is-multiple="false" :radio-list="wadingType" :radio-value.sync="form.sslz" />
            <customPopCheckbox v-if="pcdx === 'J' && pcdx !== 'N'" title="设施类别" :is-multiple="false" :radio-list="categoryList" :radio-value.sync="form.category" />
            <customPopCheckbox title="运行状态" :list="operationalStatus" :check-value.sync="form.yxzt" />
            <customPopCheckbox v-if="pcdx === 'N'" title="养殖种类" :list="yzzlDataList" :check-value.sync="form.yzzl" />
          </template>
          <template v-else>
            <div v-if="pcdx === 'rhpwk'" class="customPopCheckbox">
              <div class="checkbox-title">排污口编号</div>
              <el-input v-model="form.pwkbh" placeholder="请输入排污口编号" size="small" clearable />
            </div>
            <customPopCascade v-if="pcdx === 'rhpwk'" ref="customPopCascade" title="排污口类型" cascader-title="排污口类型" :list="pwklxListData" @change="pwklxListChange" @clearData="form.pwklx = ''" />
          </template>
          <customPopCascade ref="customPopCascade" title="行政区划" cascader-title="行政区划" :list="districtList" @change="districtChange" @clearData="form.districtCode = ''" />
        </div>
        <div class="pop-bottom">
          <van-button type="default" @click="resetSuperSearch">清空</van-button>
          <van-button type="info" @click="handleSuperSearch">确认</van-button>
        </div>
      </div>
    </van-popup>
    <!-- 重点行业下拉框 -->
    <van-popup v-model="companySelectShow" position="bottom">
      <van-picker title="请选择重点行业" show-toolbar :default-index="companySelectIndex" :columns="companySelectColumns" @cancel="companySelectShow = false" @confirm="onCompanyConfirm" />
    </van-popup>
  </div>
</template>
<script>

import CustomDetailsTopbar from '@/components/globals/custom-details-topbar.vue'
import {
  categoryList,
  enterpriseBaseInfoType,
  operationalStatus,
  pwklxListData,
  verificationDataList,
  wadingType,
  yzzlDataList
} from '@/views/special/data'
import commonList from '@/assets/mixin/commonList'
import {
  getDistrictByUser,
  getIndustryByCodeS,
  getKeyIndustry,
  getRhpwkListFun,
  getRhpwkPczz,
  getWryInformations
} from '@/api/special'
import { useFindOptionByValueRecursive } from '@/utils'
import CustomTotalNum from '@/components/globals/custom-total-num.vue'
import refHandler from '@/assets/mixin/refHandler'
import CheckSituation from '@/views/special/components/checkSituation.vue'
import CompanyInformation from '@/views/special/components/companyInformation.vue'

export default {
  components: { CompanyInformation, CheckSituation, CustomTotalNum, CustomDetailsTopbar },
  id: 'verification',
  mixins: [commonList, refHandler],
  inject: ['layout'],
  data() {
    return {
      wadingType, // 涉水类型静态数据
      operationalStatus, // 运行状态静态数据
      enterpriseBaseInfoType, // 企业基本信息类型静态数据
      pwklxListData, // 排污口类型静态数据
      categoryList, // 设施类别静态数据
      yzzlDataList, // 养殖种类静态数据
      verificationDataList: [{ value: 'rivers', label: '河流' }].concat(verificationDataList),
      activeIndex: '',
      industryNameShow: false, // 行业名称弹窗
      popupShow: false,
      companySelectShow: false,
      situationParams: {
        checkSituationShow: false, // 河流和工业企业排查情况 - 状态
        type: '', // 河流和工业企业排查情况 - 类型
        title: '默认', // 标题
        dataItem: {} // 当前项
      }, // 河流和工业企业排查情况
      companyInformationParams: {
        isShow: false, // 状态
        title: '默认', // 标题
        dataItem: {}, // 当前项
        type: '' // 类型
      }, // 企业信息抽屉
      companySelectIndex: 0,
      companySelectColumns: [],
      keyIndustries: '',
      industryListData: [], // 行业名称数据列表
      listData: [], // 表格数据
      districtList: [], // 行政区划list
      pcdx: '', // 排查类型
      total: 0,
      form: {
        pageNum: 1,
        pageSize: 10,
        yzzl: '', // 养殖种类
        pwklx: '', // 排污口类型
        pwkbh: '', // 排污口编号
        pwkmc: '', // 排污口名称
        hlmc: '', // 河流名称
        districtCode: '', // 行政区划代码
        pcQiyeName: '', // 企业名称
        tbnf: '', // 填报年份
        keylndustry: '', // 重点行业
        industry: '', // 行业名称
        g101_1: '', // 企业基本信息类型
        sslz: '', // 涉水类型
        yxzt: '', // 运行状态
        category: '' // 设施类别
      }
    }
  },
  watch: {
    $route: {
      handler(to) {
        if (to.query && to.query.sourcesName) {
          this.activeIndex = verificationDataList.findIndex(idx => idx.value === to.query.sourcesName) + 1
          this.pcdx = this.$route.query.sourcesName
          this.$nextTick(() => {
            this.scrollToSelectedFeature()
            this.getKeyIndustryHandler()
            this.getIndustryByCodeSHandler()
            this.getDistrictByUserHandler()
            this.getPageListHandler()
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    /**
     * 分页
     * @param value
     */
    handlePages(value) {
      this.form.pageNum = value
      this.getPageListHandler()
    },
    /**
     * 获取污染源列表
     */
    async getPageListHandler() {
      try {
        const api = {
          'rivers': getRhpwkPczz,
          'rhpwk': getRhpwkListFun,
          'G': getWryInformations,
          'J': getWryInformations,
          'N': getWryInformations,
          'SCYZ': getWryInformations,
          'xia': getWryInformations,
          'b': getWryInformations,
          'hai': getWryInformations,
          'stations': getWryInformations,
          'water': getWryInformations
        }
        this.$refs.customLoadmore.loadStatus = true
        this.layout.showAreaLoading(['.listInner', '.table-list'])
        this.form['pcdx'] = this.pcdx
        const { status, data } = await api[this.pcdx](this.form)
        if (status === 0 && data) {
          this.total = data.total
          this.pages = data.pages
          this.listData = this.listData.concat(data.list)
        }
        this.$refs.customLoadmore.loadStatus = false
        this.layout.hideAreaLoading(['.listInner', '.table-list'])
      } catch (err) {
        console.log(err)
      }
    },
    /**
     * 获取行政区划
     */
    async getDistrictByUserHandler() {
      try {
        const { status, data } = await getDistrictByUser({ districtCode: this.form.districtCode })
        if (status === 0 && data) {
          if (this.form.districtCode === '') {
            this.districtList = data.map(code => {
              return {
                label: code['districtName'],
                text: code['districtName'],
                value: code['districtCode']
              }
            })
          }
          if (this.form.districtCode && this.form.districtCode !== '') {
            const findItem = useFindOptionByValueRecursive(this.districtList, this.form.districtCode)
            console.log('findItem', findItem)
            if (findItem.children.length === 0 && data.length === 0) {
              delete findItem.children
            } else {
              findItem.children = data.map(list => {
                return {
                  label: list['districtName'],
                  text: list['districtName'],
                  value: list['districtCode'],
                  children: []
                }
              })
            }
          }
        }
      } catch (err) {
        console.log(err)
      }
    },
    /**
     * 获取行业名称 - 级联
     */
    async getIndustryByCodeSHandler() {
      try {
        const { status, data } = await getIndustryByCodeS({ industryCode: this.form.industry })
        if (status === 0 && data) {
          // 初始化的时候的数据结构
          if (this.form.industry === '') {
            this.industryListData = data.map(list => {
              return {
                label: list['industryTypeName'],
                text: list['industryTypeName'],
                value: list.industryTypeCode,
                children: []
              }
            })
          }
          // 生成级联
          if (this.form.industry && this.form.industry !== '') {
            const findItem = useFindOptionByValueRecursive(this.industryListData, this.form.industry)
            if (findItem.children.length === 0 && data.length === 0) {
              delete findItem.children
            } else {
              findItem.children = data.map(list => {
                return {
                  label: list['industryTypeName'],
                  text: list['industryTypeName'],
                  value: list.industryTypeCode,
                  children: []
                }
              })
            }
          }
        }
      } catch (err) {
        console.log(err)
      }
    },
    /**
     * 获取重点行业
     * @returns {Promise<void>}
     */
    async getKeyIndustryHandler() {
      try {
        const { status, data } = await getKeyIndustry()
        if (status === 0 && data) {
          this.companySelectColumns = data.map(item => {
            return {
              value: item.industryTypeCode,
              text: item['industryTypeName']
            }
          })
        }
      } catch (err) {
        console.log(err)
      }
    },
    /**
     * 单选按钮绑定值发生改变
     */
    radioChangeHandler(item, index) {
      this.pcdx = item.value
      this.activeIndex = index
      this.onCancel()
      this.scrollToSelectedFeature()
      this.handleSuperSearch()
    },
    openPopup() {
      this.popupShow = true
    },
    onCancel() {
      this.popupShow = false
    },
    /**
     * 返回工作台
     */
    back() {
      this.$router.push({
        path: '/special'
      })
    },
    /**
     * 切换污染源类型
     * @param item
     * @param index
     */
    setActiveFeature(item, index) {
      this.pcdx = item.value
      this.activeIndex = index
      this.handleSuperSearch()
    },
    getTime(val) {
      this.form.tbnf = val
    },
    /**
     * 定位到当前所选中
     */
    scrollToSelectedFeature() {
      this.$nextTick(() => {
        const selectedFeature = this.$refs.scrollContainer.querySelector('.feature.active')
        if (selectedFeature) {
          const scrollContainer = this.$refs.scrollContainer
          scrollContainer.scrollLeft = selectedFeature.offsetLeft - scrollContainer.offsetLeft
        }
      })
    },
    /**
     * 确认查询
     */
    handleSuperSearch() {
      this.superSearch = false
      this.form.pageNum = 1
      this.form.pageSize = 10
      this.listData = []
      this.getPageListHandler()
    },
    /**
     * 重置
     */
    resetSuperSearch() {
      for (const argumentsKey in this.form) {
        if (argumentsKey !== 'pageNum' || argumentsKey !== 'pageSize' || argumentsKey !== 'pcdx') {
          this.form[argumentsKey] = ''
          this.keyIndustries = ''
        } else {
          this.form.pageNum = 1
          this.form.pageSize = 10
        }
      }
      this.$refs.customPopCascade ? this.$refs.customPopCascade.clearCascader() : ''
    },
    /**
     * 确认选中重点行业
     * @param value
     */
    onCompanyConfirm(value) {
      this.form.keylndustry = value.value
      this.keyIndustries = value.text
      this.companySelectShow = false
    },
    /**
     * 行业名称发生改变
     * @param payload
     */
    cascadeChange(payload) {
      this.form.industry = payload.value
      this.getIndustryByCodeSHandler()
    },
    /**
     * 排污口类型发生改变
     * @param payload
     */
    pwklxListChange(payload) {
      console.log(payload)
      this.form.pwklx = payload.value
    },
    /**
     * 行政区划代码发生改变
     * @param payload
     */
    districtChange(payload) {
      this.form.districtCode = payload.value
    },
    /**
     * 河流和入河排污口抽屉 - 打开
     * @param row
     */
    openCheckSituationDrawer(row) {
      this.pcdx === 'rhpwk' ? this.situationParams.title = row.pwkmc : this.situationParams.title = row.hlmc
      this.pcdx === 'rhpwk' ? this.situationParams.type = 'rhpwk' : this.situationParams.type = 'rivers'
      this.situationParams.checkSituationShow = true
      this.situationParams.dataItem = row
      this.$nextTick(async() => {
        await this.$refs.checkSituationRef.getListInfo()
      })
    },
    /**
     * 河流和入河排污口抽屉关闭
     */
    checkSituationCancel() {
      this.situationParams.checkSituationShow = false
    },
    /**
     * 打开企业信息抽屉
     * @param row
     */
    async openCompanyInformationDrawer(row) {
      this.companyInformationParams.title = row['danweiName']
      this.companyInformationParams.isShow = true
      this.companyInformationParams.dataItem = row
      this.companyInformationParams.type = this.pcdx
      this.$nextTick(async() => {
        await this.$refs.companyInformationRef.getCompanyInformation(row.tbnf)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.ulBox {
  display: flex;
  overflow-x: auto;
  white-space: nowrap;
  scroll-snap-type: x mandatory;
  scrollbar-width: none;
  -ms-overflow-style: none;
  position: relative;
  .iconBox {
    position: fixed;
    background-color: white;
    height: auto;
    right: 0;
    .van-icon {
      font-size: 20px;
      padding: 0 8px;
    }
  }
  ::-webkit-scrollbar {
    display: none;
  }
  li {
    flex: 0 0 auto;
    margin-right: 10px;
    padding: 10px;
    font-size: 0.35rem;
    scroll-snap-align: start;
    span {
      padding-right: 0.25rem;
      border-right: 5px solid #cccccc;
    }
    span.active {
      color: #328bf3;
    }
  }
  li:last-child {
    margin-right: 20px;
  }
}
.ulBox::-webkit-scrollbar {
  display: none;
}
</style>
